/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.common.tool;

import cn.hutool.core.util.HexUtil;
import com.qiniu.util.Hex;
import io.swagger.annotations.ApiModelProperty;
import org.springblade.common.constant.DiskUnitEnum;
import org.springblade.common.constant.HistoryTableEnum;
import org.springblade.common.constant.PortInOutEnum;
import org.springblade.modules.desk.entity.Alerts;
import org.springblade.modules.monitor.dto.DiskDTO;
import org.springblade.modules.monitor.dto.DiskMetadata;
import org.springblade.modules.monitor.pojo.*;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 通用工具类
 *
 * @author Chill
 */
public class CommonUtil {
	public static Double fun2(Double f) {
		DecimalFormat df = new DecimalFormat("#.00");
		return Double.valueOf(df.format(f));
	}

	/**
	 * 字节 转换为B MB GB
	 *
	 * @param size 字节大小
	 * @return
	 */
	public static DiskMetadata getPrintSize(long size,String unit) {
		if(!StringUtils.isEmpty(unit)){
			if(unit.equals(DiskUnitEnum.GB.name())){
				size = size * 1024 * 1024 * 1024;
			}

			if(unit.equals(DiskUnitEnum.MB.name())){
				size = size * 1024 * 1024 ;
			}

			if(unit.equals(DiskUnitEnum.KB.name())){
				size = size * 1024 ;
			}
		}


		//获取到的size为：1705230
		//定义TB的计算常量
		long TB = 1024 * 1024 * 1024 * 1024L;
		//定义GB的计算常量
		long GB = 1024 * 1024 * 1024;
		//定义MB的计算常量
		long MB = 1024 * 1024;
		//定义KB的计算常量
		long KB = 1024;
		//格式化小数
		DecimalFormat df = new DecimalFormat("0.00");
		DiskMetadata diskMetadata = new DiskMetadata();
		String resultSize = "";
		if (size / TB >= 1) {
			diskMetadata.setSize(CommonUtil.fun2(size / (double) TB));
			diskMetadata.setUnit(DiskUnitEnum.T.name());
		} else if (size / GB >= 1) {
			diskMetadata.setSize(CommonUtil.fun2(size / (double) GB));
			diskMetadata.setUnit(DiskUnitEnum.GB.name());
		} else if (size / MB >= 1) {
			diskMetadata.setSize(CommonUtil.fun2(size / (double) MB));
			diskMetadata.setUnit(DiskUnitEnum.MB.name());
		} else if (size / KB >= 1) {
			diskMetadata.setSize(CommonUtil.fun2(size / (double) KB));
			diskMetadata.setUnit(DiskUnitEnum.KB.name());
		} else {
			diskMetadata.setSize((double) size);
			diskMetadata.setUnit(DiskUnitEnum.B.name());
		}
		return diskMetadata;
	}

	public static List<DiskDTO> transferVFSInfo(Map<String, Object> map, List<DiskDTO> diskList) {
		if (null != diskList) {
			diskList.forEach(x -> {
				Set<Map.Entry<String, Object>> entries = map.entrySet();
				entries.forEach(entry -> {
					String[] split = splitTarget(entry.getKey());
					String diskName = split[0];
					//当前磁盘名
					//磁盘名称相同
					Double value = Double.valueOf(entry.getValue().toString());
					if (x.getDiskName().equalsIgnoreCase(diskName)) {
						//使用率百分比
						if ("pused".equalsIgnoreCase(split[1])) {
							x.setDiskUsage(CommonUtil.fun2(value));
						}
					}
				});

			});
			return diskList;
		} else {
			List<DiskDTO> list = new ArrayList<>();
			Set<Map.Entry<String, Object>> entries = map.entrySet();
			Iterator<Map.Entry<String, Object>> iterator = entries.iterator();

			//去重，获取磁盘名
			Set<String> diskNames = new TreeSet<>();
			while (iterator.hasNext()) {
				Map.Entry<String, Object> next = iterator.next();
				String key = next.getKey();
				String[] split = splitTarget(key);
				String diskName = split[0];
				diskNames.add(diskName);
			}

			//再次循环，获取 total,used的磁盘值
			diskNames.forEach(x -> {
				DiskDTO ds = new DiskDTO();
				ds.setDiskName(x);
				entries.forEach(entry -> {
					String[] split = splitTarget(entry.getKey());
					//当前磁盘名
					String diskName = split[0];
					Long value = Long.valueOf(entry.getValue().toString());
					//磁盘名称相同
					if (x.equalsIgnoreCase(diskName)) {
						//总量
						if ("total".equalsIgnoreCase(split[1])) {
							DiskMetadata printSize = CommonUtil.getPrintSize(value,null);
							ds.setDiskTotal(printSize.getSize());
							ds.setDiskTotalUnit(printSize.getUnit());
							ds.setDiskInitialTotal(value);
						}

						//已使用容量
						if ("used".equalsIgnoreCase(split[1])) {
							DiskMetadata printSize = CommonUtil.getPrintSize(value,null);
							ds.setDiskUsed(printSize.getSize());
							ds.setDiskUsedUnit(printSize.getUnit());
							ds.setDiskInitialUsed(value);
						}
					}
				});
				list.add(ds);
			});
			return list;
		}
	}



	public static StorageCenterVO transferStorageCenter(List<Map<String, Object>> strValues,List<Map<String, Object>> intValues,List<Map<String, Object>> values){
		StorageCenterVO storageCenterVO = new StorageCenterVO();

		Set<String> diskIndexes = new TreeSet<>();
		List<StorageCenterDisk> disks = new ArrayList<>();

		Set<String> controllerIndexes = new TreeSet<>();
		List<StorageCenterController> controllers = new ArrayList<>();

		Set<String> serverIndexes = new TreeSet<>();
		List<StorageCenterServer> servers = new ArrayList<>();

		Set<String> volumnIndexes = new TreeSet<>();
		List<StorageCenterVolume> volumns = new ArrayList<>();

		Set<String> powerIndexes = new TreeSet<>();
		List<StorageCenterPower> powers = new ArrayList<>();

		strValues.forEach(x->{
			String[] split = splitTarget(x.get("key_").toString());
			if(x.get("key_").toString().contains("scDiskPosition[")){
//				diskIndexes.add(split[0]);
				StorageCenterDisk temp = new StorageCenterDisk();
				temp.setIndex(split[0]);
				disks.add(temp);
			}

			if(x.get("key_").toString().contains("scServerName[")){
				StorageCenterServer temp = new StorageCenterServer();
				temp.setName(split[0]);
				servers.add(temp);
			}

			if(x.get("key_").toString().contains("scVolumeName[")){
				StorageCenterVolume temp = new StorageCenterVolume();
				temp.setName(split[0]);
				volumns.add(temp);

			}

			//设备描述
			if(x.get("key_").toString().contains("deshu.system.equipname")){
				storageCenterVO.setSystemDesc(x.get("value").toString());
			}

			//厂商
			if(x.get("key_").toString().contains("deshu.system.factory")){
				storageCenterVO.setFactory(x.get("value").toString());
			}

			//serviceTag
			if(x.get("key_").toString().contains("dell.service.tag[")){
				storageCenterVO.setServiceTag(x.get("value").toString());
			}


		});

		intValues.forEach(x->{
			String[] split = splitTarget(x.get("key_").toString());
			if(x.get("key_").toString().contains("scCtrlNbr[")){
				StorageCenterController temp = new StorageCenterController();
				temp.setControllerName(split[0]);
				controllers.add(temp);
			}
		});

		StorageCenterDiskFolder diskFolder = new StorageCenterDiskFolder();
		values.forEach(x->{
			if(x.get("key_").toString().contains("scDiskFolderSUTotalSpace2[2")){
				DiskMetadata printSize = CommonUtil.getPrintSize(Double.valueOf(x.get("value").toString()).longValue(), "GB");
				diskFolder.setTotalSpace(printSize.getSize());
				diskFolder.setTotalUnit(printSize.getUnit());
			}

			if(x.get("key_").toString().contains("scDiskFolderSUAllocSpace[2")){
				DiskMetadata printSize = CommonUtil.getPrintSize(Double.valueOf(x.get("value").toString()).longValue(), "GB");
				diskFolder.setAllocSpace(printSize.getSize());
				diskFolder.setAllocUnit(printSize.getUnit());
			}

			if(x.get("key_").toString().contains("scDiskFolderSUUsedSpace2[2")){
				DiskMetadata printSize = CommonUtil.getPrintSize(Double.valueOf(x.get("value").toString()).longValue(), "GB");
				diskFolder.setUsedSpace(printSize.getSize());
				diskFolder.setUsedUnit(printSize.getUnit());
			}

			if(x.get("key_").toString().contains("scDiskFolderSUFreeSpace[2")){
				DiskMetadata printSize = CommonUtil.getPrintSize(Double.valueOf(x.get("value").toString()).longValue(), "GB");
				diskFolder.setFreeSpace(printSize.getSize());
				diskFolder.setFreeUnit(printSize.getUnit());
			}

			if(x.get("key_").toString().contains("scDiskFolderSUSpareSpace[2")){
				DiskMetadata printSize = CommonUtil.getPrintSize(Double.valueOf(x.get("value").toString()).longValue(), "GB");
				diskFolder.setSpareSpace(printSize.getSize());
				diskFolder.setSpareUnit(printSize.getUnit());
			}

		});

		storageCenterVO.setDiskFolder(diskFolder);

		//磁盘信息组装
		disks.forEach(t->{
			strValues.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scDiskPosition[")&&t.getIndex().equals(split[0])){
					t.setPosition(x.get("value").toString());
				}

			});
			intValues.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scDiskStatus[")&&t.getIndex().equals(split[0])){
					t.setStatus(Integer.valueOf(x.get("value").toString()));
				}
			});
			values.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scDiskSize[")&&t.getIndex().equals(split[0])){
					t.setSize(Double.valueOf(x.get("value").toString()));
					t.setUnit("GB");
				}
			});
		});

		storageCenterVO.setDiskList(disks);

		//控制器信息组装
		controllers.forEach(t->{
			intValues.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scCtrlStatus[")&&t.getControllerName().equals(split[0])){
					t.setStatus(Integer.valueOf(x.get("value").toString()));
				}
			});

			strValues.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scCtlrIpAddr[")&&t.getControllerName().equals(split[0])){
					t.setIpAddress(x.get("value").toString());
				}
			});

		});

		// 修改控制器名称
		controllers.forEach(x->{
			String controllerName = x.getControllerName();
				String showName = HexUtil.decodeHexStr(controllerName.replace(" ",""));
				x.setControllerName(showName);
		});

		storageCenterVO.setControllerList(controllers);

		servers.forEach(t->{
			intValues.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scServerCnctvy[")&&t.getName().equals(split[0])){
					t.setConnectivityStatus(Integer.valueOf(x.get("value").toString()));
				}

				if(key_.contains("scServerStatus[")&&t.getName().equals(split[0])){
					t.setStatus(Integer.valueOf(x.get("value").toString()));
				}
			});
		});
		storageCenterVO.setServerList(servers);

		volumns.forEach(t->{
			intValues.forEach(x->{
				String key_ = x.get("key_").toString();
				String[] split = splitTarget(key_);
				if(key_.contains("scVolumeStatus[")&&t.getName().equals(split[0])){
					t.setStatus(Integer.valueOf(x.get("value").toString()));
				}

			});
		});
		storageCenterVO.setVolumeList(volumns);

		//添加电源状态监控
		strValues.forEach(x->{
			String key_ = x.get("key_").toString();
			if(key_.contains("scCtlrPowerName")){
				StorageCenterPower power = new StorageCenterPower();
				power.setName(x.get("value").toString());
				powers.add(power);
			}
		});

		powers.forEach(x->{
			String name = x.getName();
			intValues.forEach(t->{
				String key_ = t.get("key_").toString();
				if(key_.endsWith(name.substring(name.length()-1))){
					x.setStatus(Integer.valueOf(t.get("value").toString()));
				}
			});
		});

		storageCenterVO.setPowerList(powers);
		return storageCenterVO;
	}

	public static ThreeLayerSwitchVO transferThreeLayerSwitch(List<Map<String, Object>> strValues, List<Map<String, Object>> intValues, List<Map<String, Object>> values) {

		ThreeLayerSwitchVO threeLayerSwitchVO = new ThreeLayerSwitchVO();
		List<ThreeLayerSwitchPower> powers = new ArrayList<>();
		List<ThreeLayerSwitchCPU> cpus = new ArrayList<>();
		List<ThreeLayerSwitchMem> mems = new ArrayList<>();
		List<ThreeLayerSwitchPort> ports = new ArrayList<>();
		List<String> serviceTags = new ArrayList();
		//添加电源状态监控
		strValues.forEach(x->{
			String key_ = x.get("key_").toString();
			if(key_.contains("deshu.power.util.status[")){
				ThreeLayerSwitchPower power = new ThreeLayerSwitchPower();
				power.setName(x.get("value").toString());
				powers.add(power);
			}
			//设备描述
			if(x.get("key_").toString().contains("deshu.system.equipname")){
				threeLayerSwitchVO.setSystemDesc(x.get("value").toString());
			}

			//厂商
			if(x.get("key_").toString().contains("deshu.system.factory")){
				threeLayerSwitchVO.setFactory(x.get("value").toString());
			}

			if(x.get("key_").toString().contains("dell.service.tag[")){
				serviceTags.add(x.get("value").toString());
			}
		});

		//获取serviceTag
		threeLayerSwitchVO.setServiceTag(String.join(",", serviceTags));

		powers.forEach(x->{
			String name = x.getName();
			intValues.forEach(t->{
				String key_ = t.get("key_").toString();
				if(key_.endsWith(name.substring(name.length()-1))){
					x.setStatus(Integer.valueOf(t.get("value").toString()));
				}
			});
		});

		//添加CPU状态监控
		values.forEach(x->{
			String key_ = x.get("key_").toString();
			if(key_.contains("deshu.cpu.util[")){
				ThreeLayerSwitchCPU cpu = new ThreeLayerSwitchCPU();
				cpu.setCpuUsage(Double.valueOf(x.get("value").toString()));
				cpu.setItemid(Long.valueOf(x.get("itemid").toString()));
				cpus.add(cpu);
			}
		});

		List<Long> inSpeedItems = new ArrayList<>();
		List<Long> outSpeedItems = new ArrayList<>();
		//添加mem状态监控、端口状态监控
		intValues.forEach(x->{
			String key_ = x.get("key_").toString();
			String name_ = x.get("name").toString();
			if(key_.contains("deshu.mem.util.size[")){
				String temp = splitKeytTargetCharacter(key_,"\\,")[0];
				String index = temp.substring(temp.indexOf("."));
				ThreeLayerSwitchMem mem = new ThreeLayerSwitchMem();
				DiskMetadata printSize = CommonUtil.getPrintSize(Long.valueOf(x.get("value").toString()), "MB");
				mem.setMemSize(printSize.getSize());
				mem.setMemUnit(printSize.getUnit());
				mem.setIndex(index);
				mems.add(mem);
			}

			/*'dellnet.if.status[dellNetSysIfOperStatus.2098820]'*/
			if(key_.contains("dellnet.if.status[")&&(!name_.contains("Management"))){
				ThreeLayerSwitchPort port = new ThreeLayerSwitchPort();
				port.setName(x.get("name").toString());
				String[] strings = splitKeytTargetCharacter(key_,"\\.");
				port.setIndex(strings[1]);
				port.setOperStatus(Integer.valueOf(x.get("value").toString()));
				ports.add(port);
			}

			//入端口流量
			if(key_.contains("net.if.in[ifHCInOctets")){
				inSpeedItems.add(Long.valueOf(x.get("itemid").toString()));
			}

			//出端口流量
			if(key_.contains("net.if.out[ifHCOutOctets")){
				outSpeedItems.add(Long.valueOf(x.get("itemid").toString()));
			}



		});

		threeLayerSwitchVO.setInSpeedItems(inSpeedItems);
		threeLayerSwitchVO.setOutSpeedItems(outSpeedItems);

		//获取端口需要监控的itemid
//		transferPort(ports, intValues);

		//mem 使用率
		mems.forEach(x->{
			String index = x.getIndex();
			values.forEach(t->{
				String key_ = t.get("key_").toString();
				if(key_.contains("deshu.mem.util.usage[")&&key_.contains(index)){
					x.setMemUsage(CommonUtil.fun2(Double.valueOf(t.get("value").toString())));
					x.setItemid(Long.valueOf(t.get("itemid").toString()));
				}
			});
		});

		threeLayerSwitchVO.setPowerList(powers);
		threeLayerSwitchVO.setCpuList(cpus);
		threeLayerSwitchVO.setMemList(mems);
		threeLayerSwitchVO.setPhyPortList(ports);
		return threeLayerSwitchVO;
	}



	public static SwitchVO transferSwitch(List<Map<String, Object>> strValues, List<Map<String, Object>> intValues, List<Map<String, Object>> values) {
		SwitchVO switchVO = new SwitchVO();
		List<SwitchPower> powers = new ArrayList<>();
		List<ThreeLayerSwitchCPU> cpus = new ArrayList<>();
		List<ThreeLayerSwitchMem> mems = new ArrayList<>();
		List<ThreeLayerSwitchPort> ports = new ArrayList<>();
		//添加电源状态监控
		strValues.forEach(x->{
			String key_ = x.get("key_").toString();
			//设备描述
			if(key_.contains("system.descr[")){
				switchVO.setSystemDesc(x.get("value").toString());
			}

			//serviceTag
			if(key_.contains("system.hw.serialnumber")){
				switchVO.setServiceTag(x.get("value").toString());
			}


			//厂商 TODO 判断是否存在，否则使用 Brocade
			switchVO.setFactory("Brocade");
		});


		//添加CPU状态监控
		values.forEach(x->{
			String key_ = x.get("key_").toString();
			if(key_.contains("system.cpu.util[")){
				ThreeLayerSwitchCPU cpu = new ThreeLayerSwitchCPU();
				cpu.setCpuUsage(Double.valueOf(x.get("value").toString()));
				cpu.setItemid(Long.valueOf(x.get("itemid").toString()));
				cpus.add(cpu);
			}


			if(key_.contains("vm.memory.util[")){
				ThreeLayerSwitchMem mem = new ThreeLayerSwitchMem();
				mem.setMemUsage(CommonUtil.fun2(Double.valueOf(x.get("value").toString())));
				mem.setItemid(Long.valueOf(x.get("itemid").toString()));
				mems.add(mem);
			}

			if(key_.contains("sensor.temp.value[swSensorValue.1]")){
				switchVO.setTemperature(CommonUtil.fun2(Double.valueOf(x.get("value").toString())));
			}

		});
		List<Long> inSpeedItems = new ArrayList<>();
		List<Long> outSpeedItems = new ArrayList<>();
		intValues.forEach(x->{
			String key_ = x.get("key_").toString();
			if(key_.contains("sensor.psu.status[")){
				SwitchPower power = new SwitchPower();
				power.setName(splitNameTargetCharacter(x.get("name").toString(),":")[0]);
				//由于厂商不同，需要进行特定转换
				power.setStatus(Integer.valueOf(x.get("value").toString()));
				powers.add(power);
			}

			if(key_.contains("deshu.portPhystate[")){
				ThreeLayerSwitchPort port = new ThreeLayerSwitchPort();
				port.setName(CommonUtil.splitNameTargetCharacter(x.get("name").toString(),":")[0]);
				String[] strings = splitKeytTargetCharacter(key_,"\\.");
				port.setIndex(strings[1]);
				port.setOperStatus(Integer.valueOf(x.get("value").toString()));
				ports.add(port);
			}


			//入端口流量
			if(key_.contains("net.if.in[ifHCInOctets")){
				inSpeedItems.add(Long.valueOf(x.get("itemid").toString()));
			}

			//出端口流量
			if(key_.contains("net.if.out[ifHCOutOctets")){
				outSpeedItems.add(Long.valueOf(x.get("itemid").toString()));
			}


		});
		switchVO.setInSpeedItems(inSpeedItems);
		switchVO.setOutSpeedItems(outSpeedItems);
		//对port进行排序
		List<ThreeLayerSwitchPort> sortedPorts = ports.stream().sorted(Comparator.comparing(x->
			 Integer.valueOf(x.getIndex())
		)).collect(Collectors.toList());


		//对端口状态进行转换
		//对于博科而言
		//the port:
		//noCard(1)	no card present in this switch slot;
		//noTransceiver(2)	no Transceiver module in this port.
		//noGbic(2) was used previously. Transceiver is the generic name for GBIC, SFP etc.;
		//laserFault(3)	the module is signaling a laser fault (defective Transceiver);
		//noLight(4)	the module is not receiving light;
		//noSync(5)	the module is receiving light but is out of sync;
		//inSync(6)	the module is receiving light and is in sync;
		//portFault(7)	the port is marked faulty (defective Transceiver, cable or device);
		//diagFault(8)	the port failed diagnostics (defective G_Port or FL_Port card or motherboard);
		//lockRef(9)	the port is locking to the reference signal.
		//validating(10)  Validation is in progress
		//invalidModule(11) Invalid SFP unknown(255)    unknown.
		sortedPorts.forEach(x->{
			if(x.getOperStatus().equals(2)){
				x.setOperStatus(4); //no module
			}else if(x.getOperStatus().equals(6)){
				x.setOperStatus(1); //正常状态
			}else if(x.getOperStatus().equals(3)||x.getOperStatus().equals(7)){
				x.setOperStatus(3); //problem
			}else{
				x.setOperStatus(2);
			}
		});
		//获取端口需要监控的itemid
//		transferPort(ports, intValues);
		switchVO.setPowerList(powers);
		switchVO.setCpuList(cpus);
		switchVO.setMemList(mems);
		switchVO.setPhyPortList(sortedPorts);
		return switchVO;
	}

	public static SwitchVO transferFirewall(List<Map<String, Object>> strValues, List<Map<String, Object>> intValues, List<Map<String, Object>> values) {
		SwitchVO switchVO = new SwitchVO();
		List<SwitchPower> powers = new ArrayList<>();
		List<ThreeLayerSwitchCPU> cpus = new ArrayList<>();
		List<ThreeLayerSwitchMem> mems = new ArrayList<>();
		List<ThreeLayerSwitchPort> ports = new ArrayList<>();
		//添加电源状态监控
		strValues.forEach(x->{
			String key_ = x.get("key_").toString();
			//设备描述
			if(key_.contains("system.descr[")){
				switchVO.setSystemDesc(x.get("value").toString());
			}

			//serviceTag
			if(key_.contains("system.hw.serialnumber")){
				switchVO.setServiceTag(x.get("value").toString());
			}

			//厂商 TODO 判断是否存在，否则使用 Sangfor
			switchVO.setFactory("Sangfor");
		});


		//添加CPU状态监控
		values.forEach(x->{
			String key_ = x.get("key_").toString();
			if(key_.contains("system.cpu.util")){
				ThreeLayerSwitchCPU cpu = new ThreeLayerSwitchCPU();
				cpu.setCpuUsage(Double.valueOf(x.get("value").toString()));
				cpu.setItemid(Long.valueOf(x.get("itemid").toString()));
				cpus.add(cpu);
			}


			if(key_.contains("vm.memory.util[")){
				ThreeLayerSwitchMem mem = new ThreeLayerSwitchMem();
				mem.setMemUsage(CommonUtil.fun2(Double.valueOf(x.get("value").toString())));
				mem.setItemid(Long.valueOf(x.get("itemid").toString()));
				mems.add(mem);
			}


		});

		//由于深信服防火墙并未给电源状态OID,此处直接显示正常电源状态
		SwitchPower power = new SwitchPower();
		power.setStatus(1);
		powers.add(power);

		List<Long> inSpeedItems = new ArrayList<>();
		List<Long> outSpeedItems = new ArrayList<>();
		intValues.forEach(x->{
			String key_ = x.get("key_").toString();

			if(key_.contains("net.if.status[ifOperStatus")&&x.get("name").toString().contains("Interface eth")){
				ThreeLayerSwitchPort port = new ThreeLayerSwitchPort();
				port.setName(CommonUtil.splitNameTargetCharacter(x.get("name").toString(),":")[0]);
				String[] strings = splitKeytTargetCharacter(key_,"\\.");
				port.setIndex(strings[1]);
				port.setOperStatus(Integer.valueOf(x.get("value").toString()));
				ports.add(port);
			}

			if(key_.contains("vm.memory.total[")){
				DiskMetadata printSize = CommonUtil.getPrintSize(Long.valueOf(x.get("value").toString()), null);
				ThreeLayerSwitchMem threeLayerSwitchMem = mems.get(0);
				threeLayerSwitchMem.setMemSize(printSize.getSize());
				threeLayerSwitchMem.setMemUnit(printSize.getUnit());
			}

			//入端口流量
			if(key_.contains("net.if.in[ifHCInOctets")&&x.get("name").toString().contains("Interface eth")){
				inSpeedItems.add(Long.valueOf(x.get("itemid").toString()));
			}

			//出端口流量
			if(key_.contains("net.if.out[ifHCOutOctets")&&x.get("name").toString().contains("Interface eth")){
				outSpeedItems.add(Long.valueOf(x.get("itemid").toString()));
			}

		});
		switchVO.setInSpeedItems(inSpeedItems);
		switchVO.setOutSpeedItems(outSpeedItems);

		//对port进行排序
		List<ThreeLayerSwitchPort> sortedPorts = ports.stream().sorted(Comparator.comparing(x->
			Integer.valueOf(x.getIndex())
		)).collect(Collectors.toList());

		sortedPorts.forEach(x->{
			if(x.getOperStatus().equals(1)){
				x.setOperStatus(1); //正常状态（up）
			}else{
				x.setOperStatus(2);//down（up）
			}
		});
		//获取端口需要监控的itemid transferPort(ports, intValues);
		switchVO.setCpuList(cpus);
		switchVO.setMemList(mems);
		switchVO.setPhyPortList(sortedPorts);
		return switchVO;
	}


	public static String[] splitTarget(String key) {
		int start = key.lastIndexOf("[") + 1;
		int end = key.lastIndexOf("]");
		System.out.println(key);
		if(start>=end){
			return null;
		}
		String substring = key.substring(start, end);
		String[] split = substring.split(",");
		return split;
	}

	public static String[] splitKeytTargetCharacter(String key,String character) {
		int start = key.lastIndexOf("[") + 1;
		int end = key.lastIndexOf("]");
		if(start>=end){
			return null;
		}
		String substring = key.substring(start, end);
		String[] split = substring.split(character);
		return split;
	}

	public static String[] splitNameTargetCharacter(String key,String character) {
		String[] split = key.split(character);
		return split;
	}


	public static Long getSecondFromTime(LocalDateTime time){
		return time.toEpochSecond(ZoneOffset.of("+8"));
	}

	public static LocalDateTime getTimeFromMillSecond(Long millSecond){
		LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(1000*millSecond), ZoneId.of("GMT+8"));
		return localDateTime;
	}

	public static void transferPort(List<ThreeLayerSwitchPort> ports,List<Map<String, Object>> intValues){
		ports.forEach(x->{
			List<MonitorItem> items = new ArrayList<>();
			intValues.forEach(y->{
				String key_ = y.get("key_").toString();
				//入端口流量
				if(key_.contains(x.getIndex())&&key_.contains("net.if.in[ifHCInOctets")){
					MonitorItem monitorItem = new MonitorItem();
					monitorItem.setItemid(Long.valueOf(y.get("itemid").toString()));
					monitorItem.setItemName(PortInOutEnum.IN.getItemName());
					items.add(monitorItem);
				}

				//出端口流量
				if(key_.contains(x.getIndex())&&key_.contains("net.if.out[ifHCOutOctets")){
					MonitorItem monitorItem = new MonitorItem();
					monitorItem.setItemid(Long.valueOf(y.get("itemid").toString()));
					monitorItem.setItemName(PortInOutEnum.OUT.getItemName());
					items.add(monitorItem);
				}

			});
			x.setMonitorItemList(items);
		});
	}

	public static Integer  transferHealthyValue(Integer count){
		if(count==null||count<=0){
			return 100;
		}else if(count==1){
			return 60;
		}else if(count>1){
			return 30;
		}
		return null;
	}

	public static Alerts getDefaultAlert() {
		Alerts alerts = new Alerts();
		alerts.setNoticeState(0);
		alerts.setActionid(-1L);
		alerts.setEventid(-1L);
		alerts.setClock(getSecondFromTime(LocalDateTime.now()).intValue());
		alerts.setSendto("");
		alerts.setStatus(2);
		alerts.setRetries(3);
		alerts.setError("No media defined for user.");
		alerts.setEscStep(1);
		alerts.setAlerttype(0);
		alerts.setParameters("");
		return alerts;
	}

}
